package com.filter;

import com.pojo.Admins_Accounts;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*",initParams = @WebInitParam(name = "charset",value = "utf-8"))
public class LoginFilter implements Filter {
    private String charset = "utf-8";
    public void init(FilterConfig config) throws ServletException {
        String initParam = config.getInitParameter("charset");
        if ( initParam != null && (initParam = initParam.trim()).length() != 0 ) {
            charset = initParam;
        }
    }
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest srq=(HttpServletRequest) request;
        HttpServletResponse srp=(HttpServletResponse) response;
        HttpSession session=srq.getSession();
        String admin= (String) session.getAttribute("USER_NAME");
        System.out.println("LoginFilter: "+admin);
        String path=srq.getRequestURI();
        if(path.equals("/DRUG_STORAGE_SYSTEM_war_exploded/")||path.contains("Admins_AccountsServlet")||path.endsWith(".js")||path.endsWith(".css")||path.contains("ImgCode")||path.contains("element")||path.contains("SmsUtil")||path.contains("HttpUtils")){
            chain.doFilter(request,response);
            return;
        }
        if (admin == null) {
            request.getRequestDispatcher("/Login.jsp").forward(request,response);
        }else {
            chain.doFilter(request,response);
        }
    }
}
